package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.order.BaseInfoDao;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.database.order.RoomInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.HelperUtils;
import com.haochang.chunkvod.controller.adapter.order.CustomAdapter;
import com.haochang.chunkvod.model.BaseInfo;
import com.haochang.chunkvod.model.custom.CustomDialogData;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.RoomInfo;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshBase;
import com.haochang.chunkvod.view.thirdparty.PullToRefresh.PullToRefreshGridView;
import com.haochang.chunkvod.view.vod.popupWindow.SecondMenuInfo;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/6/7 15:49
 *         自定义
 */

public class CustomActivity extends BaseActivity implements EventObserver
{
	private TitleView titleView;
	private PullToRefreshGridView mGridView;
	private CustomAdapter adapter;
	private BaseTextView tv_weChatInfo;
	private List<RoomInfo> customRoomInfoList = new ArrayList<RoomInfo>();//自定义房间列表
	private List<RoomInfo> roomInfoList = new ArrayList<RoomInfo>();//房间列表
	private List<RoomInfo> showRoomInfoList = new ArrayList<RoomInfo>();//最终显示的房间列表
	private List<RoomInfo> mRoomDataInfoList = new ArrayList<RoomInfo>();//有点餐数据的房间列表
	private List<SecondMenuInfo> sortList = new ArrayList<SecondMenuInfo>();//二级菜单信息
	private List<BaseInfo> baseInfoList = new ArrayList<BaseInfo>();//颜色信息
	private OrderData orderData;
	private CustomDialogData customDialogData;
	private boolean isShowTable = false;
	private Timer timer;
	private TimerTask timerTask;
	private String sortType = "area";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.EVENT_DESK_ID);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		timer = new Timer();
		timerTask = new TimerTask()
		{
			@Override
			public void run()
			{
				getRoomInfoData(false);
			}
		};
		timer.schedule(timerTask, 30000, 30000);
	}

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		sortList.add(new SecondMenuInfo("按进场时间排序", "begin_time", true));
		sortList.add(new SecondMenuInfo("按区域排序", "area", false));
		isShowTable = HelperUtils.getHelperAppInstance().getBValue("isShowTable", false);
		orderData = new OrderData(CustomActivity.this);
		customDialogData = new CustomDialogData(CustomActivity.this);
	}

	private void getRoomInfoData(boolean isLoading)
	{
		mRoomDataInfoList = GoodsInfoDao.getDao().queryGoodInfosByBillId();
		customRoomInfoList = RoomInfoDao.getDao().queryAll(RoomInfo.class);
		baseInfoList = BaseInfoDao.getDao().queryBuilderAll(BaseInfo.class, "is_room", !isShowTable);
		orderData.requestRoomStatus("", sortType, isLoading, isShowTable, new OrderData.IRoomStatusListener()
		{
			@Override
			public void onRequestSuccess(int task_order_count, List<RoomInfo> list, boolean clear)
			{
				if (task_order_count > 0)
				{
					tv_weChatInfo.setVisibility(View.VISIBLE);
					tv_weChatInfo.setText(String.format("有%d个待确认的微信点餐", task_order_count));
					tv_weChatInfo.setOnClickListener(mOnBaseClickListener);
				}
				showRoomInfoList.clear();
				if (!CollectionUtils.isEmpty(list))
				{
					if (clear)
						roomInfoList.clear();
					roomInfoList.addAll(list);
					if (!CollectionUtils.isEmpty(customRoomInfoList))
					{
						for (int i = 0; i < customRoomInfoList.size(); i++)
						{
							RoomInfo customInfo = customRoomInfoList.get(i);
							for (int j = 0; j < roomInfoList.size(); j++)
							{
								RoomInfo info = roomInfoList.get(j);
								if (TextUtils.equals(customInfo.getBillId(), info.getBillId()))
								{
									info.setCustom(true);
									showRoomInfoList.add(info);
									break;
								}
							}
						}
					}
					if (!CollectionUtils.isEmpty(mRoomDataInfoList))
					{
						for (int i = 0; i < mRoomDataInfoList.size(); i++)
						{
							RoomInfo dbInfo = mRoomDataInfoList.get(i);
							for (int j = 0; j < showRoomInfoList.size(); j++)
							{
								RoomInfo info = showRoomInfoList.get(j);
								if (TextUtils.equals(dbInfo.getBillId(), info.getBillId()))
								{
									info.setOrderNum(dbInfo.getOrderNum());
									break;
								}
							}
						}
					}
				}
				adapter.setBaseInfoList(baseInfoList);
				adapter.replaceAll(showRoomInfoList);
			}

			@Override
			public void onFinish()
			{
				if (mGridView.getVisibility() == View.VISIBLE && mGridView.isRefreshing())
					mGridView.onRefreshComplete();
			}
		});
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_custom);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(R.string.order).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{
				final List<String> list = new ArrayList<String>();
				list.add("显示方式=sec");
				list.add("排序方式=sec");
				if (isShowTable)
					list.add("显示房间");
				else
					list.add("显示桌台");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(CustomActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							List<SecondMenuInfo> showList = new ArrayList<SecondMenuInfo>();
							String value = HelperUtils.getHelperAppInstance().getSValue("isListView", "");
							if (TextUtils.isEmpty(value))
							{
								showList.add(new SecondMenuInfo("网格式", "", true));
								showList.add(new SecondMenuInfo("条目式", "", false));
								showList.add(new SecondMenuInfo("自定义", "", false));
							} else
							{
								showList.add(new SecondMenuInfo("网格式", "", value.equals(VodConstant.GRIDVIEW)));
								showList.add(new SecondMenuInfo("条目式", "", value.equals(VodConstant.LISTVIEW)));
								showList.add(new SecondMenuInfo("自定义", "", value.equals(VodConstant.CUSTOMVIEW)));
							}
							pop.showSecondMenuView(0, showList, true);
							pop.setPopWindowLeftListListener(new VodPopWindow.OnPopWindowLeftListListener()
							{
								@Override
								public void onSelectItem(int position)
								{
									switch (position)
									{
									case 0:
										HelperUtils.getHelperAppInstance().setValue("isListView", VodConstant.GRIDVIEW);
										toOrderHomePage();
										break;
									case 1:
										HelperUtils.getHelperAppInstance().setValue("isListView", VodConstant.LISTVIEW);
										toOrderHomePage();
										break;
									case 2:
										HelperUtils.getHelperAppInstance().setValue("isListView", VodConstant.CUSTOMVIEW);
										break;
									default:
										break;
									}
								}
							});
							break;
						case 1:
							pop.showSecondMenuView(1, sortList, true);
							pop.setPopWindowLeftListListener(new VodPopWindow.OnPopWindowLeftListListener()
							{
								@Override
								public void onSelectItem(int position)
								{
									sortType = sortList.get(position).getCode();
									getRoomInfoData(false);
								}
							});
							break;
						case 2:
							if (!isShowTable)
							{
								isShowTable = true;
								HelperUtils.getHelperAppInstance().setValue("isShowTable", true);
							} else
							{
								isShowTable = false;
								HelperUtils.getHelperAppInstance().setValue("isShowTable", false);
							}
							getRoomInfoData(false);
							break;
						case 3:
							loginOut();
							break;
						default:
							break;
						}
					}
				});
			}
		});

		mGridView = (PullToRefreshGridView) findViewById(R.id.app_grid);
		mGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
		mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView)
			{
				getRoomInfoData(false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView)
			{
			}
		});
		tv_weChatInfo = (BaseTextView) findViewById(R.id.tv_weChatInfo);
		tv_weChatInfo.setVisibility(View.GONE);
		adapter = new CustomAdapter(CustomActivity.this, R.layout.item_home_page_order_grid_layout, showRoomInfoList);
		mGridView.setAdapter(adapter);
		getRoomInfoData(true);
	}

	private void toOrderHomePage()
	{
		Intent intent = new Intent(CustomActivity.this, OrderHomePageActivity.class);
		startActivity(intent);
		finish();
	}

	/**
	 * 点击微信点餐确认
	 */
	private void onOrderWeChatClick()
	{
		Intent intent = new Intent(CustomActivity.this, OrderWeChatDetailActivity.class);
		startActivity(intent);
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.tv_weChatInfo:
				onOrderWeChatClick();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.ROOM_REMARK_REQUEST && resultCode == RESULT_OK && data != null)
		{
			String billId = data.getStringExtra(IntentKey.BILL_ID);
			String remark = data.getStringExtra(IntentKey.REMARK);
			for (RoomInfo roomInfo : roomInfoList)
			{
				if (billId.equals(roomInfo.getBillId()))
				{
					roomInfo.setRoomRemark(remark);
					break;
				}
			}
			adapter.notifyDataSetChanged();
		} else if (requestCode == IntentCode.ROOM_PEOPLE_REQUEST && resultCode == RESULT_OK && data != null)
		{
			final String billId = data.getStringExtra(IntentKey.BILL_ID);
			final String amount = data.getStringExtra(IntentKey.CUSTOM_DIALOG_CONTENT);
			customDialogData.requestModifyRoomPeoPleNum(billId, amount, new CustomDialogData.IRoomPeopleListener()
			{
				@Override
				public void onRequestSuccess()
				{
					for (RoomInfo roomInfo : roomInfoList)
					{
						if (billId.equals(roomInfo.getBillId()))
						{
							roomInfo.setRoomPeopleCount(Integer.parseInt(amount));
							break;
						}
					}
					adapter.notifyDataSetChanged();
				}
			});
		}
	}

	private void cancelTask()
	{
		if (timer != null)
		{
			timer.cancel();
			timer = null;
		}
		if (timerTask != null)
		{
			timerTask.cancel();
			timerTask = null;
		}
	}

	@Override
	public void onPause()
	{
		super.onPause();
		cancelTask();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		cancelTask();
		EventProxy.removeEventListener(IEventConstant.EVENT_DESK_ID, this);
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args) {
		switch (eventId) {
			case IEventConstant.EVENT_DESK_ID:
				String bill_id = (String) args[0];
				String room_id = (String) args[1];
				for (int i = 0; i < showRoomInfoList.size(); i++) {
					RoomInfo roomInfo = showRoomInfoList.get(i);
					if (TextUtils.equals(room_id, roomInfo.getRoomId())) {
						roomInfo.setBillId(bill_id);
						break;
					}
				}
				break;
			default:
				break;
		}
	}
}
